/*
 * Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
 */
package com.xinpan.exercise;

public class RotateList {
    public ListNode rotateRight(ListNode head, int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(n == 0 || head == null)
            return head;
        
        ListNode cur = head;
        int c = 0;
        while(cur != null)
        {
            cur = cur.next;
            c++;
        }
        n = n % c;
        if(n == 0)
            return head;
        
        cur = head;
        ListNode pre = cur;
        for(int i = 0; i < n; i++)
            cur = cur.next;

        while(cur.next != null)
        {
            pre = pre.next;
            cur = cur.next;
        }
        cur.next = head;
        head = pre.next;
        pre.next = null;
        return head;
    }
}
